<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 500 ? 500 : '100%'"
    draggable
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import type { TreeNodeData } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { addApiCategory, updateApiCategory } from '@/apis/system/api'
import { type ColumnItem, GiForm } from '@/components/GiForm'
import { useResetReactive } from '@/hooks'

interface Props {
  categorys: TreeNodeData[]
}

const props = withDefaults(defineProps<Props>(), {
  categorys: () => [],
})

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改分类' : '新增分类'))
const formRef = ref<InstanceType<typeof GiForm>>()

const [form, resetForm] = useResetReactive({})

// 转换为部门树
const deptSelectTree = computed(() => {
  const data = JSON.parse(JSON.stringify(props.categorys)) as TreeNodeData[]
  return data
  // return mapTree(data, (i) => ({
  //   key: i.id,
  //   title: i.name,
  //   children: i.children,
  // }))
})

const columns: ColumnItem[] = reactive([
  {
    label: '上级分类',
    field: 'parentId',
    type: 'tree-select',
    span: 24,
    hide: (form) => {
      return form.parentId === 0
    },
    props: {
      data: deptSelectTree,
      allowClear: true,
      allowSearch: true,
      fallbackOption: false,
      filterTreeNode(searchKey, nodeData) {
        if (nodeData.title) {
          return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
        }
        return false
      },
    },
    // rules: [{ required: true, message: '请选择上级分类' }],
  },
  { label: '分类名称', field: 'title', type: 'input', span: 24, rules: [{ required: true, message: '请输入名称' }] },
  // { label: '编码', field: 'code', type: 'input', disabled: () => isUpdate.value, rules: [{ required: true, message: '请输入编码' }] },
  {
    label: '描述',
    field: 'description',
    type: 'textarea',
    disabled: false,
    span: 24,
    props: {
      maxLength: 200,
      autoSize: { minRows: 3, maxRows: 5 },
    },
  },
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

// 保存
const save = async () => {
  const isInvalid = await formRef.value?.formRef?.validate()
  if (isInvalid) return false
  try {
    if (isUpdate.value) {
      await updateApiCategory(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addApiCategory(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (data: any) => {
  reset()
  dataId.value = data.key
  // const { data } = await getDict(id)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

  <style scoped lang="scss"></style>
